//
//  YQBaseWebViewController.m
//  CusWebView
//
//  Created by yeqiang on 2024/2/20.
//

#import "YQBaseWebViewController.h"
#import "YQCookieSyncManager.h"
#import "Masonry.h"

@interface YQBaseWebViewController ()


@end

@implementation YQBaseWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = UIColor.orangeColor;
    self.webView.navigationDelegate = self;
    self.webView.UIDelegate = self;
    [self setupViews];
    [self loadWebViewRequest];
    
}

- (void)setupViews {
    [self.view addSubview:self.webView];
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(self.view);
    }];
}

- (void)loadWebViewRequest {
    NSString *urlString = self.url.absoluteString;
    if ([urlString hasPrefix:@"file://"]) {
        [self.webView loadFileURL:self.url allowingReadAccessToURL:self.url];
    } else {
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
        // 设置当前 H5版本信息等
        // [request setValue:@"" forKey:@""];
        [self.webView loadRequest:request];
    }
}

- (void)addWebViewObserver {
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
    [self.webView addObserver:self forKeyPath:@"scrollView.contentSize" options:NSKeyValueObservingOptionNew context:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dealWithWebViewLoadErrorNotification:) name:@"webViewLoadErrorNotification" object:nil];
}

- (void)reloadWebViewWithURL:(NSURL *)url {
    self.url = url;
    [self loadWebViewRequest];
    self.webView.hidden = NO;
}

- (instancetype)initWithURL:(NSURL *)url {
    self = [super init];
    if (self) {
        self.url = url;
    }
    return self;
}

- (void)dealWithWebViewLoadErrorNotification:(NSNotification *)noti {
    
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(self.view);
    }];
    
    if (@available(iOS 11.0, *)) {
        _webView.scrollView.contentInsetAdjustmentBehavior = YES;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
}


#pragma mark - KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        [self.progressView setProgress:self.webView.estimatedProgress animated:YES];
        CGFloat delayTime = 0;
        if (self.webView.estimatedProgress < 1.0) {
            delayTime = 1- self.webView.estimatedProgress;
            return;
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayTime*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.progressView.progress = 0;
        });
    } else if ([keyPath isEqualToString:@"title"]) {
        
    } else if ([keyPath isEqualToString:@"scrollView.contentSize"]) {
        
    }
}

#pragma mark - getter

- (WKWebView *)webView {
    if (!_webView) {
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        config.processPool = [YQCookieSyncManager sharedWKCookieSyncManager].processPool;
        // 统一设置 userAgent,全局
        config.applicationNameForUserAgent = @"mobile xxxxxxx";
        WKPreferences *preferences = [[WKPreferences alloc] init];
        preferences.javaScriptCanOpenWindowsAutomatically = YES;
        preferences.minimumFontSize = 10;
        preferences.javaScriptEnabled = YES;
        config.preferences = preferences;
        WKUserContentController *userContentController = [[WKUserContentController alloc] init];
        config.allowsInlineMediaPlayback = YES;
        config.userContentController = userContentController;
        config.websiteDataStore = WKWebsiteDataStore.defaultDataStore;
        _webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
        _webView.scrollView.scrollEnabled = NO;
        
        __weak typeof (WKWebView) *weakWebView = _webView;
        [weakWebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(NSString *userAgent, NSError * _Nullable error) {
            __strong typeof (WKWebView) *strongWebView = weakWebView;
            if ([userAgent containsString:@"mobile xxxxx"]) {
                return;
            }
            // 默认 + 自定义
            NSString *webUserAgent = [NSString stringWithFormat:@"%@ %@", userAgent, @"xxxxx"];
            NSDictionary *dic = [[NSDictionary alloc] initWithObjectsAndKeys:webUserAgent, @"UserAgent", nil];
            [[NSUserDefaults standardUserDefaults] registerDefaults:dic];
            [[NSUserDefaults standardUserDefaults] synchronize];
            strongWebView.customUserAgent = webUserAgent;
        }];
    }
    return _webView;
}

- (void)resetWebView {
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [self.webView removeObserver:self forKeyPath:@"title"];
    [self.webView removeObserver:self forKeyPath:@"scrollView.contentSize"];
    
    [self.webView removeFromSuperview];
    _webView = nil;
    [self.view addSubview:self.webView];
    self.webView.UIDelegate = self;
    self.webView.navigationDelegate = self;
    [self addWebViewObserver];
    [self loadWebViewRequest];
}

- (UIProgressView *)progressView {
    if (!_progressView) {
        _progressView = [[UIProgressView alloc] init];
        _progressView.progressTintColor = UIColor.blueColor;
        _progressView.trackTintColor = UIColor.darkGrayColor;
        _progressView.hidden = YES;
    }
    return _progressView;
}

@end
